
var User = {
    id: 0,
    username: "",
    role: "",
    avatar: "public/images/avatar.png",
    fullname: "",
    point: "",
    email: "",
    address: "",
    mobile: "",
    birthday: "",
    tokenkey: "",
    guessUser: function () {
        var id = _this.Timestamp.getDateTimeMilliseconds();
        var DataUser = {id: id, username: id, role: "guess", birthday: "", point: 0, fullname: "Guest User", email: "", address: "", mobile: ""};
        _this.storage.set("userinfo", JSON.stringify(DataUser));
        return DataUser;
    },
    storageUser: function () {
        return JSON.parse(_this.storage.get("userinfo"));
    },
    isLogin: function () {
        if (this.role == "member") {
            return true;
        }

        return false;
    },
    logout: function () {
        $.extend(User, User.guessUser());
    },
    save: function (UserInfo) {
        _this.storage.set("userinfo", UserInfo);
    },
    confirmLogin: function () {
        if (this.role == "guess") {
            Dialog.showConfirm({
                title: "Thông báo",
                content: "Hãy đăng nhập để tích điểm nhận thưởng",
                buttons: [
                    {
                        id: "Confirm_Login",
                        text: "Đồng ý",
                        type: "bold"
                    },
                    {
                        id: "Confirm_Cancel",
                        text: "Bỏ qua"
                    }
                ],
                effectIn: "ZoomIn_3",
                effectOut: "ZoomOut_4",
                event: function () {
                    $("#Confirm_Login").on("tap", function () {
                        Dialog.close(function () {
                            Infobar.show();
                        });

                    });

                    $("#Confirm_Cancel").on("tap", function () {
                        Dialog.close();
                    });
                }
            });
        }
    }
};

if (_this.storage.get("userinfo") == "") {
    $.extend(User, User.guessUser());
} else {
    $.extend(User, User.storageUser());
}


var Statistic = {
    id_answered: 0,
    id_question: 0,
    status: "",
    initData: function () {
        if (this.isExist()) {
            var data = JSON.parse(_this.storage.get("laststatistic_" + Program.id_tvshow));
            this.id_answered = data.id_answered;
            this.id_question = data.id_question;
            this.status = data.status;
        } else {
            this.id_answered = 0;
            this.id_question = 0;
            this.status = "";
        }
    },
    save: function () {
        var data = {id_answered: this.id_answered, id_question: this.id_question, status: 'pending'};
        _this.storage.set("laststatistic_" + Program.id_tvshow, JSON.stringify(data));
    },
    changeStatus: function (status) {
        this.status = status;
        var data = {id_answered: this.id_answered, id_question: this.id_question, status: status};
        _this.storage.set("laststatistic_" + Program.id_tvshow, JSON.stringify(data));
    },
    isExist: function () {
        if (_this.storage.get("laststatistic_" + Program.id_tvshow) == "") {
            return false;
        } else {
            return true;
        }
    },
    statusAnswered: function (id_question) {
        if (this.isExist()) {
            if (this.id_question == id_question) {
                return this.status;
            } else {
                return "none";
            }
        } else {
            return "none";
        }
    },
    remove: function () {
        this.id_answered = 0;
        this.id_question = 0;
        this.id_question = "";
        _this.storage.remove("laststatistic_" + Program.id_tvshow);
    }
};



//////////////////////////////////////////////
//////////// Js chart biểu đồ ////////////////
//////////////////////////////////////////////
function initCharts(data, num) {
    var html = '';
    var cdm = ($(window).width() / num);
    var width = (cdm * 100) / $(window).width();
    var cH = $(".Statistic_Chart").height() - 30;
    if (data == 'start') {
        html = '<p style="margin-top: 100%;font-size: 14px;color: #FFF;"> Thống kê, đang chờ ... </p>';
        $(".Statistic_Chart").html(html);
        return false;
    }
    $(".Statistic_Chart").empty();
    for (i = 1; i <= num; i++) {
        var color = '';
        var borderheight = 0; //(data[(i-1)] * 150) / 100;
        if (borderheight >= 145) {
            //var color = 'color: #fff';
        }
        html = '<span class="Column" style="width: ' + width + '%;" id="id_' + i + '">\n\
                    <p class="Column_Innser border-' + i + ' hoverMouse" data-id="' + i + '" style="border: 0px #009600 solid;' + color + '; padding-top:' + cH + 'px;" id="chart-' + i + '">0%</p>\n\
                    <p class="Column_Desc">' + i + '</p>\n\
                </span>';
        $(".Statistic_Chart").append(html);
    }
}
function updateChart(data) {
    Toast.progressNext();
    var lenght_ = data.length;
    for (i = 1; i <= lenght_; i++) {
        var cH = $(".Statistic_Chart").height();
        var pt = data[(i - 1)];
        var color = '';
        var borderheight = (pt * cH) / 100;
        var calcPaddingTop = ((cH - ((pt * cH) / 100)) - 20);
        var height_ = calcPaddingTop < 0 ? 0 : calcPaddingTop;
        if (pt != null || pt != '' || pt != undefined) {
            $("#chart-" + i).html(pt + '%').css('color', color);
            $("#chart-" + i).animate({
                borderBottomWidth: borderheight + 'px',
                paddingTop: height_ + 'px'
            }, 100);
        }
    }

}
function format_number(dec, fix) {
    fixValue = parseFloat(Math.pow(10, fix));
    retValue = parseInt(Math.round(dec * fixValue)) / fixValue;
    return retValue;
}

var AppStatus = {
    status: _this.storage.get("AppStatus"),
    onLoad: function () {
        _this.storage("AppStatus", "onLoad");
    },
    sleep: function () {
        _this.storage.set("AppStatus", "sleep");
        location.reload();
    },
    timeout: function () {
        _this.storage.set("AppStatus", "timeout");
        location.reload();
    }
};

// Upload Image Js Base64
function loadImageFileAsURL(chose) {
    var chose = chose;
    var filesSelected = document.getElementById("photo" + chose).files;
    if (filesSelected.length > 0) {
        var fileToLoad = filesSelected[0];
        var fileReader = new FileReader();
        fileReader.onload = function (fileLoadedEvent) {
            var textAreaFileContents = document.getElementById("textAreaFileContents");
            _this.storage.set("imgbase64", fileLoadedEvent.target.result);
            $('.Avatar').css("background-image", "url(" + fileLoadedEvent.target.result + ")");
            $(".User_name").css({color: "#000000"});
        };
        fileReader.readAsDataURL(fileToLoad);
    }
}

var List = {
    initEvent: function (selector) {
        $("#page_indexhome .Header_text").off("tap");
        $("#page_indexhome .Header_text").on("tap", function () {
            Toast.notification_close();
            Toast.close();
//            console.log(PopupPanel.flag);
//            console.log(PopupPanel.isOpen());
            //console.log($(this).hasClass("active"));
            if (PopupPanel.flag == false && PopupPanel.isOpen() == false && $(this).hasClass("active") == false) {
                PopupPanel.open();

                $(this).addClass("active");
                $("#Wait_PopupPanel").css("display", "block");
                if ($('#Wait_PopupPanel .Wait_inner .spiner').length == 0) {
                    _this.uiWaitOptions.color = "#777";
                    new Spinner(_this.uiWaitOptions).spin(document.querySelector('#Wait_PopupPanel .Wait_inner'));
                }
                setTimeout(function () {
                    List.gets(function () {
                        $("#Wait_PopupPanel").css("display", "none");
                    });
                }, 200);
            } else if (PopupPanel.flag == true && PopupPanel.isOpen() == true) {
                PopupPanel.close();
                if (!$(".RefreshSlider").hasClass("loading")) {
                    loadSlide(function () {
                        $(".RefreshSlider").removeClass("loading");
                    });
                }
            }
        });

    },
    gets: function (done, error) {

        var menu_flag = _this.storage.get("menu_flag");
        var userid = User.role == "member" ? User.id : 0;

        $.ajax({
            url: _this.Base_Api + "list-show",
            timeout: 10000,
            data: {user_id: userid, flag: menu_flag},
            async: false,
            success: function (data) {
                if (data != 201) {//online
                    _this.storage.set("menu_flag", data.flag);
                    _this.storage.set("list_show", JSON.stringify(data.data));
                    loadMenu(data.data, done, error);
                    refreshSlide(data.data);
                } else {//offline
                    var listshow = _this.storage.get("list_show");
                    if (listshow != "") {
                        var data = JSON.parse(_this.storage.get("list_show"));
                        //refreshSlide(data);
                        loadMenu(data, done, error);
                    }
                }
                //_this.storage.set("ProgramList", options);
            }, error: function (jqXHR, textStatus) {
                if (typeof error == 'function') {
                    error();
                }
                //Toast.show({text: "Vui lòng kiểm tra lại Internet", id: "gv", position: "bottom"});
            }
        });

    }
};



var ProgramSlider, navSwiper;

function loadSlide(callback) {

    $(".RefreshSlider").addClass("loading");

    var menu_flag = _this.storage.get("menu_flag");
    var userid = User.role == "member" ? User.id : 0;
    $.ajax({
        url: _this.Base_Api + "list-show",
        data: {user_id: userid, flag: menu_flag},
        timeout: 15000,
        success: function (data) {
            if (data != 201) {//online
                _this.storage.set("menu_flag", data.flag);
                _this.storage.set("list_show", JSON.stringify(data.data));
                loadSlide_data(data.data, callback);
            } else {//offline
                if (ProgramSlider == undefined) {
                    var data = JSON.parse(_this.storage.get("list_show"));
                    loadSlide_data(data, callback);
                } else {
                    setTimeout(function () {
                        $(".RefreshSlider").removeClass("loading");
                    }, 1000);
                }
            }
        }, error: function (jqXHR, textStatus) {
            $(".RefreshSlider").hide();
            var errorHtml = '<div class="Error"><div><span class="fa fa-rotate-right"></span><p>Mất kết nối<em>Ấn để tải lại</em></p></div></div>';
            $("#Home .Inner").html(errorHtml);
            $(".pagination").empty();
            $(".Error div").UI_AddClassHover("hover");
            $(".Error div").on("tap", function () {
                $(this).find("span").addClass("loading");
                $(this).find("p").html("Mất kết nối<em>Xin đợi...</em>");
                setTimeout(function () {
                    loadSlide(function () {
                        $(".RefreshSlider").show();
                        $(".RefreshSlider").removeClass("loading");
                        loadTvShowRunning();
                    });
                }, 1000);
            });
            //}
        }
    });

}

function loadSlide_data(data, callback) {
    var wW = $(window).width();
    var li = "", pagination = "";
    for (var i = 0; i < data.length; i++) {
        var first = (i == 0 ? 'active-nav' : '');
        pagination += '<div class="swiper-slide ' + first + '"><span></span></div>';

        var selected = data[i].id == Program.id_tvshow ? "selected" : "";
        var followed = (data[i].follow == 1 ? "<a class='btnFollow'></a>" : "<a class='btnFollow followed'></a>") + "<div id='Preload_" + data[i].id + "' class='Preload'><div class='Preload_inner'></div></div>";
        var logo = '<div class="logo" style="background: url(' + _this.Base_Upload + data[i].logo + ') no-repeat"></div>';
        var live = data[i].starting == 1 ? "block" : "none";
        li += "<div id='tvshowid_" + data[i].id + "' class='swiper-slide " + selected + "' data-type_qa='" + data[i].type + "' data-time='" + data[i].schedule + "' data-id='" + data[i].id + "' data-name='" + data[i].name + "' " + selected + " data-id_channel='" + data[i].channel_id + "' data-background_show='" + data[i].background + "' data-logo_channel='" + data[i].logo + "' data-sound_welcome='" + data[i].sound_welcome + "' data-sound_bg='" + data[i].sound_bg + "'>\n\
                                    <div class='banner' style='width:" + wW + "px;' data-src='" + _this.Base_Upload + data[i].bg_wap + "'></div>" + logo + followed + "<button class='join' style='display:" + live + "'><span></span>Tương tác ngay</button></div>";
    }

    $("#Home .Inner").html('<div class="swiper-container banners-container"><div class="swiper-wrapper">' + li + '</div></div>');
    $("#Home .pagination").html('<div class="swiper-container swiper-nav"><div class="swiper-wrapper">' + pagination + '<div></div>');


    ProgramSlider = undefined;
    navSwiper = undefined;
    //console.log(ProgramSlider);
    if (ProgramSlider == undefined) {
        //Banners
        ProgramSlider = $('.banners-container').swiper({
            slidesPerView: 'auto',
            onSlideChangeStart: function (e) {
                updateNavPosition();
            }
        });
    } else {
        ProgramSlider.reInit();
        $(".active-nav").removeClass("active-nav");
        $(".pagination .swiper-slide:nth-child(" + (ProgramSlider.activeIndex + 1) + ")").addClass("active-nav");
    }

    if (navSwiper == undefined) {
        //Nav
        navSwiper = $('.swiper-nav').swiper({
            visibilityFullFit: true,
            slidesPerView: 'auto',
            //Thumbnails Clicks
            onSlideClick: function () {
                ProgramSlider.swipeTo(navSwiper.clickedSlideIndex);
            }
        });
    }


    //Update Nav Position
    function updateNavPosition() {
        $('.swiper-nav .active-nav').removeClass('active-nav')
        var activeNav = $('.swiper-nav .swiper-slide').eq(ProgramSlider.activeIndex).addClass('active-nav');
        if (!activeNav.hasClass('swiper-slide-visible')) {
            if (activeNav.index() > navSwiper.activeIndex) {
                var thumbsPerNav = Math.floor(navSwiper.width / activeNav.width()) - 1;
                navSwiper.swipeTo(activeNav.index() - thumbsPerNav);
            }
            else {
                navSwiper.swipeTo(activeNav.index());
            }
        }
    }


    $("#Home .banner").each(function () {
        var $this = $(this);
        var img = new Image();
        img.src = $this.data("src");
        img.onload = function () {
            $this.css({
                'background-image': 'url(' + img.src + ')',
                'background-size': 'cover'
            }).addClass("fadeIn animated");
        };
        img.error = function () {

        };
    });

    setTimeout(function () {
        $(".Slide").removeClass("empty");
    }, 1000);
    if (typeof callback == 'function')
        callback();

    $("#Home .join").UI_AddClassHover("hover");
    $("#Home .join").off("tap");
    $("#Home .join").on("tap", function (e) {
        var $join = $(this);
        $join.hide();
        Toast.button({position: "bottom"});
        Toast.buttonLoad("Tải gói chương trình...");
        var $this = $(this).parent(".swiper-slide");
        function _loadTvshow() {

            Toast.notification_close();
            var id_channel = $this.data("id_channel");
            var id_tvshow = $this.data("id");
            var name = $this.data("name");
            var background_show = $this.data("background_show");
            var logo_channel = $this.data("logo_channel");
            var time = $this.data("time");
            var type_qa = $this.data("type_qa");
            var sound_welcome = $this.data("sound_welcome");
            var sound_bg = $this.data("sound_bg");

            socket.io.disconnect();
            $("#page_indexstatistic").empty();

            var _data = {
                id_channel: id_channel,
                id_tvshow: id_tvshow,
                name: name,
                background_show: background_show,
                logo_channel: logo_channel,
                time: time,
                type_qa: type_qa,
                sound_welcome: sound_welcome,
                sound_bg: sound_bg
            };
            Template.save(_data);
            Template.init(_data);


            $.get('app/index/index.html', function (html) {
                $("#page_indexindex").html(html);
                Template.active("page_indexindex", "offline", function () {
                    $join.show();
                    _this.redirect("index/index");
                    Toast.close();
                }, function () {
                    Toast.close();
                    $join.show();
                });
            });

        }

        if (socket != null) {
            _loadTvshow();
        } else {
            var timeout = setInterval(function () {
                if (socket != null) {
                    console.log(socket);
                    clearTimeout(timeout);
                    _loadTvshow();
                }
            }, 1000);
        }



    });

    $(".btnFollow").UI_AddClassHover("hover");
    $(".btnFollow").off("tap");
    $(".btnFollow").on("tap", function (e) {

        if (User.isLogin()) {
            var $this = $(this);
            if (!$this.hasClass("active")) {
                $this.addClass("active");
                $this.parent().find(".Preload").show();
                if ($this.parent().find(".Preload .spinner").length == 0) {
                    var id = $this.parent().data("id");
                    _this.uiWaitOptions.color = "#ddd";
                    new Spinner(_this.uiWaitOptions).spin(document.querySelector('#Preload_' + id + ' .Preload_inner'));
                }

                $.ajax({
                    url: _this.Base_Api + "follow",
                    timeout: 10000,
                    data: {user_id: User.id, id_tvshow: $this.parent(".swiper-slide").data("id")},
                    success: function (data) {
                        _this.storage.set("menu_flag", 0);
                        _this.storage.set("menu_flag", 0);

                        $this.removeClass("active");
                        $this.parent().find(".Preload").hide();
                        if (data.status == 200) {
                            $this.removeClass("followed");
                        } else if (data.status == 201) {
                            $this.addClass("followed");
                        }
                    }, error: function (jqXHR, textStatus) {
                        //$this.removeClass("active");
                        if (textStatus == "timeout") {
                            Toast.show({text: "Kết nối quá lâu, vui lòng thử lại.", id: "gv"});
                        } else {
                            Toast.show({text: "Không có kết nối.", id: "gv"});
                        }
                    }
                });
            }

        } else {
            Toast.show({text: "Vui lòng đăng nhập để theo dõi chương trình.", id: "gv"});
        }

        e.preventDefault();
        return false;
    });
}

function loadTvShowRunning() {
    if (_this.getParam("back") != "true") {

        $.get(_this.Base_Api + "tv-show-is-run", function (data) {

            if (data.starting == 1) {
                var _data = {
                    id_channel: data.channel_id,
                    id_tvshow: data.id,
                    name: data.name,
                    background_show: data.background,
                    logo_channel: data.logo,
                    time: data.schedule,
                    type_qa: data.type,
                    sound_welcome: data.sound_welcome,
                    sound_bg: data.sound_bg
                };
                Template.save(_data);
                Template.init(_data);

                Program.is_question_recieved = false; //đánh dấu real time đã nhận rồi socket muộn ko nhận nữa
                Statistic.initData();
                Program.LastQuestion.init();

                function _loadTvshow() {
                    if (!$("#page_indexindex").hasClass("page_active")) {
                        $.get('app/index/index.html', function (html) {
                            $("#page_indexindex").html(html);
                            Template.active("page_indexindex", "offline", function () {
                                Toast.close();
                                Toast.progress({text: "Tải chương trình đang phát sóng...", width: 160, height: 101});

                                setTimeout(function () {
                                    _this.redirect("index/index");
                                    /*
                                     *@jointvshow Tham gia phòng 
                                     *@connecttwo Nhận socket sau
                                     */
                                    socket.emit('jointvshow', data.id, User.id);
                                    socket.emit('connecttwo', data.id);
                                    Toast.progressNext();
                                    PopupPanel.close();
                                }, 1500);
                            });
                        });
                    }
                }
                if (socket != null && $(".Toast_message").length == 0) {
                    _loadTvshow();
                } else {
                    var timeout = setInterval(function () {
                        if (socket != null && $(".Toast_message").length == 0) {
                            //console.log(socket);
                            clearTimeout(timeout);

                            _loadTvshow();
                        }
                    }, 500);
                }
            }
        });
    }
}


//Đồng bộ trạng thái join chương trình
function refreshSlide(data) {
    if (data == undefined) {
        var flag = _this.storage.get("menu_flag");
        $.ajax({
            url: _this.Base_Api + "list-show?user_id=" + User.id + "&flag=" + flag,
            timeout: 10000,
            success: function (data_online) {
                if (data_online != 201) {
                    data = data_online.data;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].starting == 0) {
                            $("#tvshowid_" + data[i].id + " .join").fadeOut();
                        } else {
                            $("#tvshowid_" + data[i].id + " .join").css("display", "block");
                        }
                    }
                }

            }, error: function (jqXHR, textStatus) {
            }
        });
    } else {
        for (var i = 0; i < data.length; i++) {
            if (data[i].starting == 0) {
                $("#tvshowid_" + data[i].id + " .join").css("display", "none");
            } else {
                $("#tvshowid_" + data[i].id + " .join").css("display", "block");
            }
        }
    }

}


function cacheImage(options) {
    //_this.Base_Upload
    console.log(options);
}


function loadMenu(data, done) {
    var li = "";
    for (var i = 0; i < data.length; i++) {
        var selected = data[i].id == Program.id_tvshow ? "selected" : "";
        var followed = (data[i].follow == 1 ? "<a class='btnFollow'></a>" : "<a class='btnFollow followed'></a>") + "<div id='Preload__" + data[i].id + "' class='Preload'><div class='Preload_inner'></div></div>";
        var live = data[i].starting == 1 ? "<div class='schedule playing'>Đang tương tác</div>" : "<div class='schedule clearfix'><span class='icon-clock'></span><span class='text'>" + data[i].schedule + "</span></div>";
        li += "<li class='" + selected + "' data-starting='" + data[i].starting + "' data-type_qa='" + data[i].type + "' data-time='" + data[i].schedule + "' data-id='" + data[i].id + "' data-name='" + data[i].name + "' " + selected + " data-id_channel='" + data[i].channel_id + "' data-background_show='" + data[i].background + "' data-logo_channel='" + data[i].logo + "' data-sound_welcome='" + data[i].sound_welcome + "' data-sound_bg='" + data[i].sound_bg + "'>\n\
                                  <div class='inside'>\n\
                        <div class='relative'>\n\
                            " + followed + "\n\
                            <div class='image' style='background: url(" + _this.Base_Upload + data[i].avatar_wap + ")'></div>\n\
                            <div class='info'>\n\
                                <div class='logo' style='background: url(" + _this.Base_Upload + data[i].logo + ") no-repeat'></div>\n\
                                " + live + "\n\
                            </div>\n\
                        </div>\n\
                    </div>\n\
                   </li>";
    }

    $(".UI_PopupPanel .Scroll_Inner").html("<ul class='ListView'>" + li + "</ul>");
    if (typeof done == 'function') {
        done();
    }

    $(".btnFollow").UI_AddClassHover("hover");
    $(".ListView .btnFollow").off("tap");
    $(".ListView .btnFollow").on("tap", function (e) {
        if (User.isLogin()) {
            var $this = $(this);
            if (!$this.hasClass("active")) {
                $this.addClass("active");
                $this.parents("li").find(".Preload").show();
                if ($this.parent().find(".Preload .spinner").length == 0) {
                    var id = $this.parents("li").data("id");
                    _this.uiWaitOptions.color = "#ddd";
                    new Spinner(_this.uiWaitOptions).spin(document.querySelector('#Preload__' + id + ' .Preload_inner'));
                }
                $.ajax({
                    url: _this.Base_Api + "follow",
                    timeout: 10000,
                    data: {user_id: User.id, id_tvshow: $this.parents("li").data("id")},
                    success: function (data) {
                        _this.storage.set("menu_flag", 0);
                        _this.storage.set("menu_flag", 0);
                        $this.removeClass("active");
                        $this.parents("li").find(".Preload").hide();
                        if (data.status == 200) {
                            $this.removeClass("followed");
                            $("#tvshowid_" + id + " .btnFollow").removeClass('followed');
                        } else if (data.status == 201) {
                            $this.addClass("followed");
                            $("#tvshowid_" + id + " .btnFollow").addClass('followed');
                        }
                    }, error: function (jqXHR, textStatus) {
                        //$this.removeClass("active");
                        if (textStatus == "timeout") {
                            Toast.show({text: "Kết nối quá lâu, vui lòng thử lại.", id: "gv"});
                        } else {
                            Toast.show({text: "Không có kết nối.", id: "gv"});
                        }
                    }
                });
            }

        } else {
            Toast.show({text: "Vui lòng đăng nhập để theo dõi chương trình.", id: "gv"});
        }

        e.preventDefault();
        return false;
    });

    $(".ListView li .image").off("tap");
    $(".ListView li .image").on("tap", function (e) {
        var $this = $(this).parents("li");
        if (!$(this).parents("li").hasClass("selected")) {
            if ($this.data("starting") == 1) {

                $(".ListView li.selected").removeClass("selected");
                $this.addClass("selected");
                Toast.button({position: "bottom"});
                Toast.buttonLoad("Tải gói chương trình...");

                function _loadTvshow() {
                    Toast.notification_close();
                    var id_channel = $this.data("id_channel");
                    var id_tvshow = $this.data("id");
                    var name = $this.data("name");
                    var background_show = $this.data("background_show");
                    var logo_channel = $this.data("logo_channel");
                    var time = $this.data("time");
                    var type_qa = $this.data("type_qa");
                    var sound_welcome = $this.data("sound_welcome");
                    var sound_bg = $this.data("sound_bg");

                    $("#page_indexstatistic").empty();


                    //console.log(Program.id_tvshow);


                    var _data = {
                        id_channel: id_channel,
                        id_tvshow: id_tvshow,
                        name: name,
                        background_show: background_show,
                        logo_channel: logo_channel,
                        time: time,
                        type_qa: type_qa,
                        sound_welcome: sound_welcome,
                        sound_bg: sound_bg
                    };
                    Template.save(_data);
                    Template.init(_data);

                    socket.io.disconnect();

                    $.get('app/index/index.html', function (html) {
                        $("#page_indexindex").html(html);
                        Template.active("page_indexindex", "offline", function () {
                            _this.redirect("index/index");
                            Toast.close();
                            PopupPanel.close();
                        });
                    });
                }

                if (socket != null) {
                    _loadTvshow();
                } else {
                    var timeout = setInterval(function () {
                        if (socket != null) {
                            //console.log(socket);
                            clearTimeout(timeout);
                            _loadTvshow();
                        }
                    }, 1000);
                }


            } else {
                var index = $this.index();
                PopupPanel.close();
                setTimeout(function () {
                    ProgramSlider.swipeTo(index);
                }, 500);
            }
        } else {
            //PopupPanel.close();
        }
    });

    $(".ListView li .info").off("tap");
    $(".ListView li .info").on("tap", function (e) {
        var time = $(this).parents("li").data("time");
        Toast.button({text: time, timeout: 5000, id: "gv"});
    });
}

/*
 *@send_tokenkey user login 
 */
function send_tokenkey(key) {
    User.tokenkey = key;
    var userid = null;
    if (User.isLogin()) {
        userid = User.id;
    }
    var link = _this.Base_Api + 'get-key?user_id=' + userid + '&key=' + key + '&type=' + (_this.appOs == "ios" ? 1 : 2);
    if (key != "") {
        $.ajax({
            url: link,
            type: "GET",
            timeout: 11000,
            data: null,
            success: function (data) {
                //console.log(data); //nếu unchange thì lấy từ db change thì lấy ol
                // alert('success: '+link);
            },
            error: function (e) {
                //console.log('go offline to get story lits');
                // alert('fail');
            }
        });
    }
}

var SocketConnection = function (success) {
    var count = 0;

    var createConnect = function (data, count, success) {
        var socketUrl = data[count];
        $.ajax({
            url: socketUrl + '/ping',
            timeout: 15000,
            success: function (result) {
                success(socketUrl);
            },
            error: function (result) {
                //console.log('timeout/error');
                if (count < data.length) {
                    count++;
                    createConnect(data, count, success);
                }
            }
        });
    };
    //balance
    $.getJSON(_this.Base_Url + "get-socket/index.php?type=jo9fNz10", function (data) {
        createConnect(data, count, success);
    });
};